package com.leetcode.partition1;

import com.leetcode.common.ListNode;

/**
 * @author `RKC`
 * @date 2021/8/3 9:10
 */
public class LC2两数相加 {

    public static ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        return recursion(l1, l2);
    }

    //递归法
    private static ListNode recursion(ListNode l1, ListNode l2) {
        int sum = l1.val + l2.val;
        int next1 = sum / 10;
        ListNode current = new ListNode(sum % 10);
        //同时遍历l1和l2，将next1加其l1上。对于l1和l2不齐的结点，使用0补充
        if (l1.next != null || l2.next != null || next1 > 0) {
            if (l1.next != null) l1 = l1.next;
            else l1 = new ListNode(0);              //l1到达了链表尾部

            if (l2.next != null) l2 = l2.next;
            else l2 = new ListNode(0);

            l1.val += next1;
            current.next = recursion(l1, l2);
        }
        return current;
    }

    //迭代法
    private static ListNode method1(ListNode l1, ListNode l2) {
        int sum = 0, next1 = 0;
        ListNode result = new ListNode();
        ListNode current = result;
        while (l1 != null && l2 != null) {
            sum = l1.val + l2.val + next1;
            current.next = new ListNode(sum % 10);
            next1 = sum / 10;
            l1 = l1.next;
            l2 = l2.next;
            current = current.next;
        }
        //l1没有遍历完则进行处理l1
        while (l1 != null) {
            sum = l1.val + next1;
            current.next = new ListNode(sum % 10);
            next1 = sum / 10;
            l1 = l1.next;
            current = current.next;
        }
        //l2的处理
        while (l2 != null) {
            sum = l2.val + next1;
            current.next = new ListNode(sum % 10);
            next1 = sum / 10;
            l2 = l2.next;
            current = current.next;
        }
        if (next1 > 0) current.next = new ListNode(next1);
        return result.next;
    }

    public static void main(String[] args) {

    }
}
